package commons.r;

import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;

/**
 * commons.r.R
 * User: hly
 * Date: 2024/12/09 9:56
 * motto:   逆水行舟不进则退
 * Description:
 * Version: v1.0
 */
@Data
public class R<T> implements Serializable {
    private  Integer  code;
    private  String  msg;
    private   T  data;

    public static <T> R<T> success(T data) {

        R<T> r = new R<>();
        r.setMsg("success");
        r.setCode(200);
        r.setData(data);
        return r;
    }

    /*返回成功的方法没有参数*/
    public static <T> R<T> success() {
        R<T> r = new R<>();
        r.setMsg("success");
        r.setCode(200);
        r.setData(null);
        return r;
    }

    /*返回成功的方法没有参数*/
    public static <T> R<T> success(T data, String msg) {
        R<T> r = new R<>();
        r.setMsg(msg);
        r.setCode(200);
        r.setData(data);
        return r;
    }

    /*返回失败的方法*/
    public static <T> R<T> failed() {
        R<T> r = new R<>();
        r.setMsg("failed");
        r.setCode(500);
        r.setData(null);
        return r;
    }

    public static <T> R<T> failed(String msg) {
        R<T> r = new R<>();
        r.setMsg(msg);
        r.setCode(500);
        r.setData(null);
        return r;
    }

    public static <T> R<T> failed(Integer code, String msg){
        R<T> r = new R<>();
        r.setCode(code);
        r.setMsg(msg);
        r.setData(null);
        return r;
    }
    /**
     *   code 是20000 是正常的
     *   msg 是操作成功
     *    data 没有要响应的数据
     * @return
     */
    public static  R  ok(){
        R   r=new  R();
        r.code=20000;
        r.msg="操作成功";
        return   r;
    }

    /**
     *   code 是20000 是正常的
     *   msg 是操作成功
     * @param data data 有要响应的数据
     * @return
     */
    public static  R  ok(Object  data){
        R   r=new  R();
        r.code=20000;
        r.msg="操作成功";
        r.data=data;
        return   r;
    }

    public static   R  ok(String   msg){
        R r = new R();
        r.code=20000;
        r.msg=msg;
        return  r;
    }

    public static   R  ok(String msg,Object  data){
        R r = new R();
        r.code=20000;
        r.msg=msg;
        r.data=data;
        return  r;
    }

    public static R  error(){
        R r = new R();
        r.code=-1;
        r.msg="失败";
        return  r;
    }

    public static  R  error(String   msg){
        R r = new R();
        r.code=-1;
        r.msg=msg;
        return  r;
    }

    public  R addData(String key, Object value) {
        if (this.data==null){
            //这个吧Data 变成  Map
            this.data= (T) new HashMap<>();
            ((HashMap<String, Object>) this.data).put(key,value);
        }else if(this.data instanceof  HashMap){
            ((HashMap<String, Object>) this.data).put(key,value);
        }else {
            throw new RuntimeException("R结果集设置错误");
        }
        return  this;
    }
}
